package com.chatdating.controller;

import com.chatdating.service.BaiduIdCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/card")
public class BaiduIdCardController {

    @Autowired
    private BaiduIdCardService baiduIdCardService;

    /**
     * 接收前端上传的身份证图片文件
     */
    @PostMapping("/idcard")
    public ResponseEntity<Map<String, Object>> recognizeIdCard(@RequestParam("image") MultipartFile image) {
        try {
            String accessToken = baiduIdCardService.getAccessToken();
            if (accessToken == null) {
                return ResponseEntity.status(500).body(Collections.singletonMap("error", "无法获取Access Token"));
            }

            // 将 MultipartFile 转换为 Base64 字符串
            String imageBase64 = Base64.getEncoder().encodeToString(image.getBytes());

            // 固定识别身份证正面
            Map<String, Object> result = baiduIdCardService.identifyIdCard(accessToken, imageBase64, "front");
            return ResponseEntity.ok(result);
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Collections.singletonMap("error", "文件处理失败"));
        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(500).body(Collections.singletonMap("error", "身份证识别失败"));
        }
    }


// 接收前端请求体
    public static class IdCardRequest {
        private String image;

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }
    }
}

